package com.aiyige.page.globalsearch.adapter;

import android.app.Activity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.city.model.City;
import com.aiyige.model.User;
import com.aiyige.model.sns.Follow;
import com.aiyige.page.globalsearch.model.SearchData;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.AfterFilter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class SearchAdapter extends BaseQuickAdapter<SearchData, BaseViewHolder> {
    Activity activity;

    public SearchAdapter(Activity activity) {
        super(new LinkedList<SearchData>());
        this.activity = activity;
    }


    @Override
    protected int getDefItemViewType(int position) {
        return getItem(position).getType();
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder;
        switch (viewType) {
            case SearchData.TYPE_INFO:
                baseViewHolder = new InfoVH(getItemView(R.layout.global_search_info_item, parent));
                break;
            case SearchData.TYPE_USER:
                baseViewHolder = new UserVH(getItemView(R.layout.global_search_user_item, parent));
                break;
            case SearchData.TYPE_VIDEO:
                baseViewHolder = new VideoVH(getItemView(R.layout.global_search_video_item, parent));
                break;
            case SearchData.TYPE_LEARN_VIDEO:
                baseViewHolder = new LearnVideoVH(getItemView(R.layout.global_search_learn_video_item, parent));
                break;
            case SearchData.TYPE_MAJOR_COURSE:
                baseViewHolder = new MajorCourseVH(getItemView(R.layout.global_search_major_course_item, parent));
                break;
            case SearchData.TYPE_SPECIAL_TOPIC:
                baseViewHolder = new SpecialTopicVH(getItemView(R.layout.global_search_special_topic_item, parent));
                break;
            case SearchData.TYPE_PHOTO:
                baseViewHolder = new PhotoVH(getItemView(R.layout.global_search_photo_item, parent));
                break;
            default:
                baseViewHolder = new BaseViewHolder(getItemView(R.layout.wild_card_item, parent));
                break;
        }
        return baseViewHolder;
    }

    @Override
    protected void convert(BaseViewHolder helper, SearchData item) {
        switch (item.getType()) {
            case SearchData.TYPE_INFO:
                ((InfoVH) helper).bindData(item);
                break;
            case SearchData.TYPE_USER:
                ((UserVH) helper).bindData(item);
                break;
            case SearchData.TYPE_VIDEO:
                ((VideoVH) helper).bindData(item);
                break;
            case SearchData.TYPE_LEARN_VIDEO:
                ((LearnVideoVH) helper).bindData(item);
                break;
            case SearchData.TYPE_MAJOR_COURSE:
                ((MajorCourseVH) helper).bindData(item);
                break;
            case SearchData.TYPE_SPECIAL_TOPIC:
                ((SpecialTopicVH) helper).bindData(item);
                break;
            case SearchData.TYPE_PHOTO:
                ((PhotoVH) helper).bindData(item);
                break;
        }
    }


    public class UserVH extends BaseViewHolder {
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.nameTv)
        TextView nameTv;
        @BindView(R.id.followLayout)
        LinearLayout followLayout;
        @BindView(R.id.followedLayout)
        LinearLayout followedLayout;
        @BindView(R.id.mutualfollowedLayout)
        LinearLayout mutualfollowedLayout;
        @BindView(R.id.followNumTv)
        TextView followNumTv;
        @BindView(R.id.fanNumTv)
        TextView fanNumTv;
        @BindView(R.id.dynamicNumTv)
        TextView dynamicNumTv;
        @BindView(R.id.goodsNumTv)
        TextView goodsNumTv;
        SearchData data;

        public UserVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            GlideUtil.with(itemView.getContext())
                    .loadAvatar(data.getUser().getAvatar())
                    .into(avatarIv);
            nameTv.setText(Html.fromHtml(data.getUser().getAccount()));
            followNumTv.setText(StringUtils.formatNum(data.getUser().getStatisticsBackup().getFollowCount()));
            fanNumTv.setText(StringUtils.formatNum(data.getUser().getStatisticsBackup().getFollowersCount()));
            dynamicNumTv.setText(StringUtils.formatNum(data.getUser().getStatisticsBackup().getDynamicCount()));
            goodsNumTv.setText(StringUtils.formatNum(data.getUser().getStatisticsBackup().getProductCount()));
            try {
                if (AccountUtil.isLogin() && AccountUtil.getCurrentUser().getId().equals(data.getUser().getId())) {
                    hideAllFollow();
                } else if (!TextUtils.isEmpty(data.getUser().getMineBackup().getUserFollowId()) && data.getUser().getMineBackup().isMutualFollower()) {
                    showMutualFollowedLayout();
                } else if (!TextUtils.isEmpty(data.getUser().getMineBackup().getUserFollowId())) {
                    showFollowedLayout();
                } else {
                    showFollowLayout();
                }
            } catch (Exception e) {
                showFollowLayout();
            }
        }

        public void showFollowLayout() {
            followLayout.setVisibility(View.VISIBLE);
            followedLayout.setVisibility(View.GONE);
            mutualfollowedLayout.setVisibility(View.GONE);
        }

        public void showFollowedLayout() {
            followLayout.setVisibility(View.GONE);
            followedLayout.setVisibility(View.VISIBLE);
            mutualfollowedLayout.setVisibility(View.GONE);
        }

        public void showMutualFollowedLayout() {
            followLayout.setVisibility(View.GONE);
            followedLayout.setVisibility(View.GONE);
            mutualfollowedLayout.setVisibility(View.VISIBLE);
        }

        public void hideAllFollow() {
            followLayout.setVisibility(View.GONE);
            followedLayout.setVisibility(View.GONE);
            mutualfollowedLayout.setVisibility(View.GONE);
        }


        @OnClick({R.id.containerLayout, R.id.followLayout, R.id.followedLayout, R.id.mutualfollowedLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    ARouter.getInstance()
                            .build(ARouterConfig.UserPage)
                            .withString("userId", data.getUser().getId())
                            .navigation();
                    break;
                case R.id.followLayout:
                    if (AccountUtil.isLogin()) {
                        new AddFollowTask(activity, getAdapterPosition() - getHeaderLayoutCount()).execute();
                    } else {
                        ARouter.getInstance()
                                .build(ARouterConfig.LoginPage)
                                .navigation();
                    }
                    break;

                case R.id.followedLayout:
                case R.id.mutualfollowedLayout:
                    if (AccountUtil.isLogin()) {
                        new DeleteFollowTask(activity, getAdapterPosition() - getHeaderLayoutCount()).execute();
                    } else {
                        ARouter.getInstance()
                                .build(ARouterConfig.LoginPage)
                                .navigation();
                    }
                    break;
            }
        }
    }


    public class InfoVH extends BaseViewHolder {
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        SearchData data;

        public InfoVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            Glide.with(itemView.getContext())
                    .load(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .apply(RequestOptions.placeholderOf(R.drawable.default_image_bg))
                    .into(coverIv);
            Glide.with(itemView.getContext())
                    .load(data.getMoment().getCreatorBackup().getAvatar())
                    .apply(RequestOptions.circleCropTransform())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            watchNumTv.setText(String.format(StringUtils.getString(R.string.watch_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getViewCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }

    public class PhotoVH extends BaseViewHolder {
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.photoNumTv)
        TextView photoNumTv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        SearchData data;

        public PhotoVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            Glide.with(itemView.getContext())
                    .load(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .apply(RequestOptions.placeholderOf(R.drawable.default_image_bg))
                    .into(coverIv);
            Glide.with(itemView.getContext())
                    .load(data.getMoment().getCreatorBackup().getAvatar())
                    .apply(RequestOptions.circleCropTransform())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            photoNumTv.setText(String.format(StringUtils.getString(R.string.total_photo_num), data.getMoment().getMediaSummary().getCount()));
            watchNumTv.setText(String.format(StringUtils.getString(R.string.watch_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getViewCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }

    public class VideoVH extends BaseViewHolder {
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.episodeTv)
        TextView episodeTv;
        @BindView(R.id.durationTv)
        TextView durationTv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        SearchData data;

        public VideoVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            GlideUtil.with(itemView.getContext())
                    .loadCover(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .into(coverIv);
            GlideUtil.with(itemView.getContext())
                    .loadAvatar(data.getMoment().getCreatorBackup().getAvatar())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            episodeTv.setText(String.format(StringUtils.getString(R.string.total_episode), data.getMoment().getMediaSummary().getCount()));
            durationTv.setText(StringUtils.formatMediaDurationMS(data.getMoment().getMediaSummary().getDuration()));
            watchNumTv.setText(String.format(StringUtils.getString(R.string.watch_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getViewCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }

    public class SpecialTopicVH extends BaseViewHolder {

        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        SearchData data;

        public SpecialTopicVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            Glide.with(itemView.getContext())
                    .load(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .apply(RequestOptions.placeholderOf(R.drawable.default_image_bg))
                    .into(coverIv);
            Glide.with(itemView.getContext())
                    .load(data.getMoment().getCreatorBackup().getAvatar())
                    .apply(RequestOptions.circleCropTransform())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            watchNumTv.setText(String.format(StringUtils.getString(R.string.watch_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getViewCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }

    public class LearnVideoVH extends BaseViewHolder {
        @BindView(R.id.linePriceContainer)
        View linePriceContainer;
        @BindView(R.id.linePriceTv)
        TextView linePriceTv;
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.episodeTv)
        TextView episodeTv;
        @BindView(R.id.durationTv)
        TextView durationTv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.freeTv)
        TextView freeTv;
        @BindView(R.id.priceTv)
        TextView priceTv;
        @BindView(R.id.priceLayout)
        LinearLayout priceLayout;
        @BindView(R.id.priceContainer)
        FrameLayout priceContainer;
        @BindView(R.id.butNumTv)
        TextView butNumTv;
        SearchData data;

        public LearnVideoVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            GlideUtil.with(itemView.getContext())
                    .loadCover(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .into(coverIv);
            GlideUtil.with(itemView.getContext())
                    .loadAvatar(data.getMoment().getCreatorBackup().getAvatar())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            episodeTv.setText(String.format(StringUtils.getString(R.string.total_episode), data.getMoment().getMediaSummary().getCount()));
            durationTv.setText(StringUtils.formatMediaDurationMS(data.getMoment().getMediaSummary().getDuration()));

            priceLayout.setVisibility(View.VISIBLE);
            freeTv.setVisibility(View.INVISIBLE);
            if (data.getMoment().getOnSalesBackup().hasLinePrice()) {
                linePriceContainer.setVisibility(View.VISIBLE);
                linePriceTv.setText(StringUtils.priceFormat(data.getMoment().getCommodityBackup().getPrice()));
                priceTv.setText(StringUtils.priceFormat(data.getMoment().getOnSalesBackup().getPrice()));
            } else {
                linePriceContainer.setVisibility(View.INVISIBLE);
                priceTv.setText(StringUtils.priceFormat(data.getMoment().getCommodityBackup().getPrice()));
            }
            butNumTv.setText(String.format(StringUtils.getString(R.string.buy_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getSellCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }

    public class MajorCourseVH extends BaseViewHolder {
        @BindView(R.id.linePriceContainer)
        View linePriceContainer;
        @BindView(R.id.linePriceTv)
        TextView linePriceTv;
        @BindView(R.id.coverIv)
        ImageView coverIv;
        @BindView(R.id.locationIv)
        ImageView locationIv;
        @BindView(R.id.locationTv)
        TextView locationTv;
        @BindView(R.id.durationTv)
        TextView durationTv;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.avatarIv)
        ImageView avatarIv;
        @BindView(R.id.authorName)
        TextView authorName;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.freeTv)
        TextView freeTv;
        @BindView(R.id.priceTv)
        TextView priceTv;
        @BindView(R.id.priceLayout)
        LinearLayout priceLayout;
        @BindView(R.id.priceContainer)
        FrameLayout priceContainer;
        @BindView(R.id.buyNumTv)
        TextView buyNumTv;
        SearchData data;

        public MajorCourseVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(SearchData searchData) {
            data = searchData;
            GlideUtil.with(itemView.getContext())
                    .loadCover(ListUtil.getFirstItem(data.getMoment().getCover()) == null ? "" : ListUtil.getFirstItem(data.getMoment().getCover()))
                    .into(coverIv);
            GlideUtil.with(itemView.getContext())
                    .loadAvatar(data.getMoment().getCreatorBackup().getAvatar())
                    .into(avatarIv);
            authorName.setText(Html.fromHtml(data.getMoment().getCreatorBackup().getName()));
            priceLayout.setVisibility(View.VISIBLE);
            freeTv.setVisibility(View.INVISIBLE);
            if (data.getMoment().getOnSalesBackup().hasLinePrice()) {
                linePriceContainer.setVisibility(View.VISIBLE);
                linePriceTv.setText(StringUtils.priceFormat(data.getMoment().getCommodityBackup().getPrice()));
                priceTv.setText(StringUtils.priceFormat(data.getMoment().getOnSalesBackup().getPrice()));
            } else {
                linePriceContainer.setVisibility(View.INVISIBLE);
                priceTv.setText(StringUtils.priceFormat(data.getMoment().getCommodityBackup().getPrice()));
            }
            buyNumTv.setText(String.format(StringUtils.getString(R.string.buy_num), StringUtils.formatNum(data.getMoment().getStatisticsBackup().getSellCount())));
            titleTv.setText(Html.fromHtml(data.getMoment().getTitle()));
            durationTv.setText(String.format(StringUtils.getString(R.string.course_num_label), String.valueOf(data.getMoment().getMediaSummary().getDuration())));
            try {
                City city = DummyDataUtil.getCityById(data.getMoment().getCityId());
                locationTv.setText(city.getCity());
            } catch (Exception e) {
                locationTv.setText("");
            }
        }

        @OnClick({R.id.containerLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.containerLayout:
                    Router.start(data.getMoment().getRouter());
                    break;
            }
        }
    }


    public class AddFollowTask extends SafeAsyncTask<Object, Object, Object> {
        int position;
        SearchData source;
        Follow result;

        public AddFollowTask(Activity activity, int position) {
            super(activity, R.string.loading);
            this.position = position;
            source = getItem(position);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {

            } else {
                try {
                    if (getItem(position).getUser().getId().equals(source.getUser().getId())) {
                        SearchData searchData = getItem(position);
                        searchData.getUser().getMineBackup().setUserFollowId(result.getId());
                        searchData.getUser().getMineBackup().setMutualFollower(result.getMutualFollower());
                        setData(position, source);
                    }
                } catch (Exception e) {

                }
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().addFollow(Follow.newBuilder()
                        .beFollowedId(source.getUser().getId())
                        .followerId(AccountUtil.getCurrentUser().getId())
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Follow follow = JSON.parseObject(json, Follow.class);
                if (follow == null) {
                    throw new Exception("添加关注失败");
                }
                result = new Follow(follow);
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    public class DeleteFollowTask extends SafeAsyncTask<Object, Object, Object> {
        int position;
        SearchData source;

        public DeleteFollowTask(Activity activity, int position) {
            super(activity, R.string.loading);
            this.position = position;
            source = getItem(position);
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .deleteFollow(source.getUser().getMineBackup().getUserFollowId())
                        .execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }


        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
            } else {
                try {
                    if (getItem(position).getUser().getId().equals(source.getUser().getId())) {
                        SearchData searchData = getItem(position);
                        searchData.getUser().getMineBackup().setUserFollowId("");
                        searchData.getUser().getMineBackup().setMutualFollower(false);
                        setData(position, searchData);
                    }
                } catch (Exception e) {

                }
            }
        }
    }


}
